package com.rfchina.okr.xianren.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.kit.HashKit;
import com.jfinal.plugin.activerecord.Model;
import com.rfchina.okr.xianren.base.ErrorRunTimeException;

public class MyUtil {

	static String number = "1234567890";

	public static String random(int length) {
		Random r = new Random();

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < length; i++) {
			sb.append(number.charAt(r.nextInt(number.length())));
		}

		return sb.toString();
	}

	public static void verification(boolean flag, String msg) {
		verification(flag, msg, 404);
	}

	public static void verification(boolean flag, String msg, int code) {
		if (flag) {
			throw new ErrorRunTimeException(code, msg);
		}
	}

	public static String getRealIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	private static String SALT_PUBLIC = "cn.liyicun.jylawyer.base";

	public static String buildPasword(String password, String salt) {
		return HashKit.md5(password + SALT_PUBLIC + salt);
	}

	public static boolean paswordEquals(String password, Model<?> data) {
		// System.out.println(password + " --- " + buildPasword(password,
		// data.getStr("salt")));
		return buildPasword(password, data.getStr("salt")).equals(data.getStr("passwd"));
	}

	public static String datasToStr(String[] keywords) {
		String keyword = "";
		if (keywords != null) {
			Set<String> positionset = new HashSet<String>(Arrays.asList(keywords));
			for (String string : positionset) {
				keyword += "," + string;
			}
			if (keyword.startsWith(","))
				keyword = keyword.substring(1);
		}
		return keyword;
	}

	public static void error(int code, String msg) {
		throw new ErrorRunTimeException(code, msg);
	}
}
